import cv2
import numpy as np
import json
'''
Created on Nov 5, 2012

@author: x220
'''

    
class contourDetectionCanny:
    def __init__(self,debug=False,thrs1=3500, thrs2=4500,contourSize=1000):
        self.debug=debug
        self.oldframe = None
        self.thrs1 = thrs1
        self.thrs2 = thrs2
        self.controurSize = contourSize
        if(self.debug):
            cv2.namedWindow('edge')
            cv2.createTrackbar('thrs1', 'edge', 2000, 2500, self._callbak)
            cv2.createTrackbar('thrs2', 'edge', 4000, 4200, self._callbak)
            cv2.createTrackbar('controurSize', 'edge', 0, 200, self._callbak)
    
    
    def _callbak(self,*arg):
        self.thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
        self.thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
        self.controurSize = cv2.getTrackbarPos('controurSize', 'edge')
        self.proces(self.oldframe)
    
    def proces(self, frame):  
        self.oldframe = frame  
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        edge = cv2.Canny(gray, self.thrs1, self.thrs2, apertureSize=5)
        if(self.debug):
            cv2.imshow('edge',edge)
        contours, temp = cv2.findContours(edge, cv2.RETR_LIST ,cv2.CHAIN_APPROX_NONE)
        contoursWithCorrectSize = []  
        if(len(contours) != 0):
            for contour in contours:
                if(cv2.contourArea(contour)>self.controurSize):
                        for cordinate in contour:
                            contoursWithCorrectSize.append(int(cordinate[0][0]))
                            contoursWithCorrectSize.append(int(cordinate[0][1]))
        return contoursWithCorrectSize
    
    def getJsonString(self,data):
        return str(json.dumps(data))
        
    def show(self,contours,frame=None):
        if frame==None:
            frame = np.empty(self.oldframe.shape)
        for i in range(0,len(contours),2):
            cord = (contours[i],contours[i+1])
            cv2.line(frame, cord, cord,(0,0,255),2)
        cv2.imshow("contours", frame)